package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.cache.redis.service.IStrategyStatisVOService;
import cn.wolfcode.wolf2w.cache.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.RedisKeys;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisDataInListener implements ApplicationListener<ContextRefreshedEvent>{

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVOService strategyStatisVOService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("-----------start--------");
        // 查询monggodb 中所有攻略
        List<Strategy> list = strategyService.list();

        // 将攻略对象转化成vo 对象
        // 先遍历攻略集合
        for (Strategy st: list) {
            // 判断vo对象是否已经存在redis中,如果存在说明不需要再初始化了
            if(strategyStatisVOService.isStrategyVOExists(st.getId())){
                continue;// 跳过
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            // 再把攻略对象的属性初始化到vo 对象中
            BeanUtils.copyProperties(st,vo);
            // 把攻略id 放入vo对象中
            vo.setStrategyId(st.getId());
            // 把每一条初始化后的vo 更新进redis中
            strategyStatisVOService.setStrategyStatisVo(vo);
        }
        System.out.println("-----------end--------");
    }
}
